<?php

namespace App\Jobs;

use App\Models\User;
use App\Models\GoldEnd;
use App\Models\GoldProduct;
use App\Services\SettleGoldRecordReselling\SettleGoldRecordReselling;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use App\Events\GoldRecordPaidEvent;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use App\Services\MakeGoldRecord\MakeGoldRecord;
use Illuminate\Support\Facades\DB;

class RobotTerminateJob implements ShouldQueue
{
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	public User $robot;
	public GoldEnd $goldEnd;

	public function __construct(User $robot, GoldEnd $end)
	{
		$this->robot = $robot;
		$this->goldEnd = $end;
	}

	public function handle()
	{
        $user = $this->robot;

        if ($user->name != 'terminator') return;

		$p = $this->goldEnd->goldProduct;

        if (! $p) return;

        $record = app(MakeGoldRecord::class, [
            'user' => $user,
            'unpaidCacheId' => $p
        ])->make();

        if ($record) {
            event(new GoldRecordPaidEvent($record));
            app(SettleGoldRecordReselling::class, ['record' => $record])->run();
        }

        DB::transaction(function () use ($p) {
            $p->update(['disabled_at' => Carbon::now()]);
            $this->goldEnd->update(['ended_at' => Carbon::now()]);
        });
	}
}
